package com.rs.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.rs.entity.ExamWork;
import com.rs.entity.Response;
import com.rs.entity.login.User;
import com.rs.entity.vo.ExamWorkVO;
import com.rs.service.ExamWorkService;
import com.rs.util.ZpiUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

@Controller
@RequestMapping("examWork")
public class ExamWorkController {


    @Autowired
    private ExamWorkService examWorkService;

    @RequestMapping("/upload")
    @ResponseBody
    public Response<String> getByKey(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
        if(!file.isEmpty()){
            //可以对user做一些操作如存入数据库
            //以下的代码是将文件file重新命名并存入Tomcat的webapps目录下项目的下级目录fileDir
            String fileRealName = file.getOriginalFilename();                   //获得原始文件名;
            fileRealName=StringFilter(fileRealName);
            int pointIndex =  fileRealName.indexOf(".");                        //点号的位置
            String fileSuffix = fileRealName.substring(pointIndex);             //截取文件后缀
            String fileName = fileRealName.substring(0, pointIndex);             //截取文件名，不包括后缀
            //生成文件的前缀包含连字符
            String currentDateTimeStr = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN);
            //文件存取名,老师的编号
            User user = (User)request.getSession().getAttribute("user");
            String savedFileName = user.getUsername()+"/"+fileName+"_"+currentDateTimeStr+fileSuffix;
            //获取服务器指定文件存取路径
            String realPath = request.getSession().getServletContext().getRealPath("");
            String savePath = realPath+"/upload";
            String resultPath = "/upload/"+savedFileName;

            File file1 = new File(savePath);
            if (!file1.exists()) {
                file1.mkdir();
            }
            File file2 = new File(savePath+"/"+user.getUsername());
            if (!file2.exists()) {
                file2.mkdir();
            }

            File savedFile = new File(savePath, savedFileName);
            boolean isCreateSuccess = savedFile.createNewFile();
            if(isCreateSuccess){
                //转存文件
                file.transferTo(savedFile);
            }
            return Response.success(fileRealName+","+resultPath);
        }
        return Response.fail("上传失败！");
    }
    //文件名替换特殊字符
     public String StringFilter(String str)  {
       try {
           String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
           Pattern p = Pattern.compile(regEx);
           Matcher m = p.matcher(str);
           return m.replaceAll("").trim();
       } catch (Exception e) {
           e.printStackTrace();
       }
       return  str;
   }

    @RequestMapping("/save")
    @ResponseBody
    public int save(@RequestBody ExamWorkVO examWorkVO){

        return examWorkService.save(examWorkVO);
    }


    @RequestMapping("/index")
    public String index(Model model) {
        return "examwork/index";
    }


    @RequestMapping("/list")
    @ResponseBody
    public Response list(long page, long limit,String name,Integer type) {
        if(type==null){
            type=0;
        }
        List<ExamWork> classes = examWorkService.getList(page,limit,name,type);
        return Response.list(classes,examWorkService.getSum(name,type));
    }

    @RequestMapping("/selectExam")
    public String  selectExam(Model model ,Integer id){
        //查询当前考试
        ExamWork examWork=examWorkService.getOne(id);
        model.addAttribute("exam",examWork);
        //查询所有学生
        List<Map> maps=examWorkService.getKsStudents(id);
        model.addAttribute("maps",maps);
        return "examwork/selectExam";
    }

    @RequestMapping("/del")
    @ResponseBody
    public void delExam(int id) {

        examWorkService.delExam(id);
    }

    @RequestMapping("/batchDownload")
    @ResponseBody
    public Response batchDownload(HttpServletRequest request, @RequestBody List<String> urls) {

        String realPath = request.getSession().getServletContext().getRealPath(""); //获取服务器指定文件存取路径
        String inputUrl = "";
        for (String url : urls){
            url = realPath+url;
            inputUrl += "|"+url;
        }
        String uus="";
        if(urls.size()>0){
            String uu=urls.get(0);
            if(uu.split("/").length>1){
                String[] s=uu.split("/");
                 uus=s[2];
            }
        }

        String path = "/upload/temp/";
        String saveName = uus+".zip";
        String savePath = realPath+File.separator+"upload"+File.separator+"temp";

        File file1 = new File(savePath);
        if (!file1.exists()) {
            file1.mkdir();
        }

        inputUrl = inputUrl.substring(1);
        try {
            ZpiUtils.zip(inputUrl, savePath+File.separator+saveName, saveName);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.fail("失败");

        }

        return Response.success(path+saveName);
    }

}
